package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    private final static String url = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO);
        if (openid == null) {
            throw new LoginFailedException("用户登录失败");
        }
        User user = userMapper.getByOpenid(openid);

        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }




    private String getOpenid(UserLoginDTO userLoginDTO) {
        String appid = weChatProperties.getAppid();
        String secret = weChatProperties.getSecret();
        HashMap<String, String> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("appid", appid);
        stringObjectHashMap.put("secret", secret);
        stringObjectHashMap.put("js_code", userLoginDTO.getCode());
        stringObjectHashMap.put("grant_type", "authorization_code");
        String s;
        try {
            s = HttpClientUtil.doGet(url, stringObjectHashMap);
        } catch (Exception e) {
            throw new RuntimeException("微信服务端请求失败");
        }

        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        return openid;
    }



}
